package com.sx.medicinecard.utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;

public class JSONParameterUtils {
    /**
     * 按照 ASCII 字典序排序 JSON 参数，并根据指定规则进行拼接
     *
     * @param
     * @param appSecret  用于拼接的 appSecret
     * @return 拼接后的字符串
     */
    public static String sortAndConcatJson(JSONObject jsonObject, String appSecret) {
        // 解析 JSON 字符串为 JSONObject
       // JSONObject jsonObject = JSONObject.parseObject(jsonString);
        Map<String, Object> sortedMap = new TreeMap<>();

        // 遍历 JSON 对象的键值对，按照 ASCII 字典序排序
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            if (entry.getValue() instanceof JSONObject) {
                // 如果是嵌套的 JSON 对象，也需要排序
                Map<String, Object> nestedSortedMap = new TreeMap<>(((Map<String, Object>) entry.getValue()));
                sortedMap.put(entry.getKey(), JSONObject.toJSONString(nestedSortedMap));
            } else {
                sortedMap.put(entry.getKey(), entry.getValue().toString());
            }
        }

        // 构建拼接字符串
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(appSecret);
        for (Map.Entry<String, Object> entry : sortedMap.entrySet()) {
            stringBuilder.append(entry.getKey()).append(entry.getValue());
        }

        return stringBuilder.toString();
    }

    public static String generateSignForBizContent(JSONObject bizContentJson,String secretKey) throws JsonProcessingException {
        // Filter out empty values
        Map<String, Object> filteredParams = new HashMap<>();
        for (String key : bizContentJson.keySet()) {
            Object value = bizContentJson.get(key);
            if (value != null && !value.toString().isEmpty()) {
                filteredParams.put(key, value);
            }
        }

        // Sort by ASCII order of parameter names
        List<String> sortedKeys = new ArrayList<>(filteredParams.keySet());
        Collections.sort(sortedKeys);

        // Build the string to be signed
        StringBuilder signBuilder = new StringBuilder();
        ObjectMapper objectMapper = new ObjectMapper();

        for (String key : sortedKeys) {
            Object value = filteredParams.get(key);
            signBuilder.append(key).append("=").append(value.toString()).append("&");
        }

        // Append the secret key
        signBuilder.append("key=").append(secretKey);

        // Here, for simplicity, I use the raw string as the signature.
        // Normally you would apply some cryptographic hash function like MD5, SHA256, etc.
        return signBuilder.toString();
    }

    public static String getStringByJsonParam(JSONObject jsonObject,String key){
        //取出所有的key组成一个列表
        List<String> keyList = new ArrayList<>(jsonObject.keySet());

        //将key的列表按照ASCII顺序排列
        Collections.sort(keyList, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                if (s1.isEmpty() && s2.isEmpty()) {
                    return 0;
                } else if (s1.isEmpty()) {
                    return -1;
                } else if (s2.isEmpty()) {
                    return 1;
                }
                return s1.compareTo(s2);
            }
        });

        //拼装加密前的数据
        StringBuilder needMd5 = new StringBuilder();
        for(int i=0;i<keyList.size();i++){
            if(i!=0){
                needMd5.append("&");
            }
            needMd5.append(keyList.get(i)).append("=").append(jsonObject.get(keyList.get(i)));
        }
        needMd5.append("&key=").append(key);
        return needMd5.toString();
    }
    /**
     * 示例：测试工具类功能
     */
    public static void main(String[] args) {
        String appSecret = "39dd81b61c0e191ff7ddae6923629b3e";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userPhone","1");


        // String jsonString = "{\"appId\":\"ykqhuaan2vx02F11\",\"paramJson\":{\"channelCode\":\"8831\",\"endTime\":1754928000,\"startTime\":1723478400,\"userId\":\"a763c5b25cdb45af879cc6f6044feca2\",\"userPhone\":\"15656569371\"},\"timestamp\":1723530689}";

        String result = null;
        try {
            result = JSONParameterUtils.getStringByJsonParam(jsonObject, appSecret);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("拼接后的字符串：" + result);
    }

}
